import axios from "axios";
//import { ElMessage } from "element-plus";  不需要再引入了
import router from "@/router";
import { getToken } from "@/utils/token"
//创建axios对象
const request = axios.create({
  baseURL: "http://localhost:8080",
  withCredentials:false, // 跨域请求时不发送凭证信息(不携带cookie)
  timeout: 5000         //超时时间
});
//配置请求头参数
request.defaults.headers["Content-Type"] = "application/json;charset=utf-8";
//配置请求的拦截器
// let token = '';
request.interceptors.request.use(
    config=>{
        //如果有token，则请求头中添加token，token需要从pinia中获取
        if(getToken("token")){ 
            config.headers["Authorization"] =  getToken("token");
        }
        
        return config;
    },
    error=>{
        return Promise.reject(error);
    }
)
//配置响应拦截器
request.interceptors.response.use(
    response=>{
        //对响应数据进行操作
        let {msg,code} = response.data;
        console.log(msg,code);
        if (code == 200) {
          // ElMessage.success(msg);
          return response.data;
        } else if (code == 500) {
          ElMessage.error("服务端异常!!!");
        } else if (code == 405) {
          ElMessage.error(msg);
          return response.data;
        } else if (code == 406) {
          ElMessage.error(msg);
          return response.data;
        } else if (code == 407) {
          ElMessage.error(msg);
          return response.data;
        } else if (code == 401) {
          ElMessage.error(msg);
          return response.data;
        } else if (code == 403) {
          ElMessage.error("登陆过期!!!");
          //清除pinia、sessionStorage中的数据
          window.sessionStorage.clear();
          router.push('/login');

        }
        return Promise.reject(new Error(msg));

    },
    error=>{
        ElMessage.error("没有操作权限!!!");
        window.sessionStorage.clear();
        router.push("/login");
        return Promise.reject(error);
    }
)

export default request;